package com.auto.survey.base

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.auto.survey.log.AppLogger
import com.auto.survey.log.CrashHandler
import com.auto.survey.log.MemoryLeakDetector

class CustomApplication : Application() {

    companion object {
        private lateinit var instance: CustomApplication
        fun getContext(): Context = instance.applicationContext
        private val visibleActivities = mutableListOf<Activity>()
        // 判断应用是否在前台
        val isAppInForeground: Boolean
            get() = visibleActivities.isNotEmpty()

        // 获取当前 Activity
        val currentActivity: Activity?
            get() = visibleActivities.lastOrNull()
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

        // 初始化日志系统
        AppLogger.getInstance(this)

        // 安装崩溃捕获器
        CrashHandler.install()

        // 启动内存监控（可选）
        MemoryLeakDetector.startMonitoring()

        registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {
            override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}

            override fun onActivityStarted(activity: Activity) {
                visibleActivities.add(activity)
            }

            override fun onActivityResumed(activity: Activity) {}

            override fun onActivityPaused(activity: Activity) {}

            override fun onActivityStopped(activity: Activity) {
                visibleActivities.remove(activity)
            }

            override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

            override fun onActivityDestroyed(activity: Activity) {}
        })
    }


}